# -*- coding: utf-8 -*-

from odoo import models, fields, api
import urllib2
import urllib
import ssl
import json
import pycurl
import StringIO
from jpype import *
import jpype
import os.path
from datetime import datetime, timedelta, time
import pytz

import logging

from odoo.http import request

_logger = logging.getLogger(__name__)


class test(models.Model):
    _name = 'watermeters.test'
    _rec_name = 'device_id'

    testname = fields.Char(string=u'Test')
    watermeter_id = fields.Many2one('watermeters.watermeter', store=True)
    table_no = fields.Integer(string=u'表号')
    balance = fields.Float(string=u'剩余金额', digits=(16, 3))
    sum_of_amount = fields.Float(string=u'累充金额', digits=(16, 2))
    sum_of_flow = fields.Float(string=u'累计流量', digits=(16, 1))
    IMEI = fields.Char(string=u'设备唯一标识')
    table_state = fields.Char(string=u'表状态')
    device_id = fields.Char(string=u'设备号')
    upload_time = fields.Char(string=u'上报时间')

    # 获取token
    @api.multi
    def btn_get_token(self):
        appId = self.env['ir.config_parameter'].get_param('app_id')
        secret = self.env['ir.config_parameter'].get_param('secret')
        url = "https://180.101.147.89:8743/iocm/app/sec/v1.1.0/login"

        if not jpype.isJVMStarted():
            config_file = os.environ["MX_CONFIG"]
            jarpath = os.path.join(os.path.abspath('.'), config_file)
            startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % jarpath)

        Authentication = jpype.JClass('com.huawei.service.appAccessSecurity.Authentication')
        auth = Authentication()
        response = auth.getToken(java.lang.String(appId), java.lang.String(secret), java.lang.String(url))

        # shutdownJVM()

        response_dict = json.loads(response)
        accessToken = response_dict['accessToken']
        return accessToken

    # 批量删除订阅
    @api.multi
    def delete_subscribptions(self):
        appId = self.env['ir.config_parameter'].get_param('app_id')
        callbackurl = "https://watermeter.mxnet.cn:443/watermeter/subscription/callback"
        notifyType = "deviceDataChanged"
        accessToken = self.btn_get_token()
        url = "https://180.101.147.89:8743/iocm/app/sub/v1.2.0/subscriptions?appId=%s&notifyType=%s&callbackUrl=%s" % (
            appId, notifyType, callbackurl)

        if not jpype.isJVMStarted():
            config_file = os.environ["MX_CONFIG"]
            jarpath = os.path.join(os.path.abspath('.'), config_file)
            startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % jarpath)

        SubscribeNotification = jpype.JClass('com.huawei.service.dataCollection.SubscribeNotification')
        subscribeNotification = SubscribeNotification()
        response = subscribeNotification.deleteSubscriptions(java.lang.String(appId), java.lang.String(accessToken),
                                                             java.lang.String(url))
        # jpype.shutdownJVM()
        _logger.info(response)
        return response

    # 订阅平台消息
    @api.multi
    def btn_subscribe_msg(self):
        appId = self.env['ir.config_parameter'].get_param('app_id')
        accessToken = self.btn_get_token()
        url = "https://180.101.147.89:8743/iocm/app/sub/v1.1.0/subscribe"
        callbackurl = "https://watermeter.mxnet.cn:443/watermeter/subscription/callback"

        if not jpype.isJVMStarted():
            config_file = os.environ["MX_CONFIG"]
            jarpath = os.path.join(os.path.abspath('.'), config_file)
            startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % jarpath)

        SubscribeNotification = jpype.JClass('com.huawei.service.dataCollection.SubscribeNotification')
        subscribeNotification = SubscribeNotification()
        response = subscribeNotification.subscribeCallback(java.lang.String(appId), java.lang.String(accessToken),
                                                           java.lang.String(callbackurl), java.lang.String(url))
        # jpype.shutdownJVM()
        _logger.info(response)
        return response

    @api.multi
    def queryhistory(self):
        appId = self.env['ir.config_parameter'].get_param('app_id')
        accessToken = self.btn_get_token()
        deviceId = "4d3ce342-8980-4e60-a5b8-99640637dc28"
        gatewayId = deviceId

        if not jpype.isJVMStarted():
            config_file = os.environ["MX_CONFIG"]
            jarpath = os.path.join(os.path.abspath('.'), config_file)
            startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % jarpath)

        QueryHistoryData = jpype.JClass('com.huawei.service.dataCollection.QueryDeviceHistoryData')
        queryHistoryData = QueryHistoryData()
        response = queryHistoryData.queryDeviceHistoryData(java.lang.String(appId), java.lang.String(accessToken),
                                                           java.lang.String(deviceId), java.lang.String(gatewayId))
        # jpype.shutdownJVM()
        print response
        datas = json.loads(response)
        deviceDataHistoryDTOs = datas.get('deviceDataHistoryDTOs')
        data = deviceDataHistoryDTOs[0].get('data')
        table_no = data.get('meterNumber')
        balance = data.get('accountBalance')
        sum_of_amount = data.get('totalAmount')
        sum_of_flow = data.get('meterValue')
        table_state = data.get('meterStatus')

        sql = "update watermeters_watermeter set table_no='%s',balance=%s,sum_of_amount=%s," \
              "sum_of_flow=%s,table_state='%s' " \
              "from watermeters_watermeter a where a.device_id='%s'" % (
                  table_no, balance, sum_of_amount, sum_of_flow, table_state, deviceId)
        request.env.cr.execute(sql)
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'watermeters.watermeter',
            'view_mode': 'tree',
            'view_type': 'tree',
            'target': 'self',
        }

    @api.model
    def subscribecallback(self, data):
        if not data:
            _logger.info(u"没有参数")
            back = '{"callback": "没有有参数"}'
            return json.dumps(back)
        else:
            _logger.info(data)
            kw = json.loads(data)
            deviceId = kw.get('deviceId')
            service = kw.get('service')
            time = service.get('eventTime')
            tz = pytz.timezone('Asia/Shanghai')
            # upload_time = time[0:4] + '-' + time[4:6] + '-' + time[6:8] + ' ' + time[9:11] + ':' + time[11:13] + ':' + time[13:15]
            utctime = datetime(int(time[0:4]), int(time[4:6]), int(time[6:8]), int(time[9:11]), int(time[11:13]),
                               int(time[13:15]), tzinfo=pytz.timezone('UTC'))
            upload_time = utctime.astimezone(tz).strftime("%Y-%m-%d %H:%M:%S")
            _logger.info(upload_time)
            deviceData = service.get('data')

            table_no = deviceData.get('meterNumber')
            balance = deviceData.get('accountBalance')
            sum_of_amount = deviceData.get('totalAmount')
            sum_of_flow = deviceData.get('meterValue')
            table_state = deviceData.get('meterStatus')
            meter = self.env['watermeters.watermeter'].search([('device_id', '=', deviceId)])
            # 保存每一条数据，写进test模型
            save_sql = "insert into watermeters_test (table_no,balance,sum_of_amount,sum_of_flow,table_state,device_id,upload_time) " \
                       "values (%s,%s,%s,%s,'%s','%s','%s')" % (
                           table_no, balance, sum_of_amount, sum_of_flow, table_state, deviceId, upload_time)
            self.env.cr.execute(save_sql)
            if not meter:
                sql = "insert into watermeters_watermeter (table_no,balance,sum_of_amount,sum_of_flow,table_state,device_id,upload_time) " \
                      "values (%s,%s,%s,%s,'%s','%s','%s')" % (
                          table_no, balance, sum_of_amount, sum_of_flow, table_state, deviceId, upload_time)
                self.env.cr.execute(sql)
            else:
                sql = "update watermeters_watermeter set table_no='%s',balance=%s,sum_of_amount=%s," \
                      "sum_of_flow=%s,table_state='%s',upload_time='%s' " \
                      "from watermeters_watermeter a where watermeters_watermeter.device_id='%s'" % (
                          table_no, balance, sum_of_amount, sum_of_flow, table_state, upload_time, deviceId)
                self.env.cr.execute(sql)
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'watermeters.watermeter',
            'view_mode': 'tree',
            'view_type': 'tree',
            'target': 'new',
        }
